package controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import model.Setting;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import appmodel.JsonModel;
import common.StringUtil;
import service.SettingService;

@Controller
@RequestMapping("setting")
@SuppressWarnings({"rawtypes","unused"})
public class SettingController {
	@Autowired
	private SettingService settingService;

	@RequestMapping("/list")
	public String list(HttpServletRequest request) {

		List settList = settingService.selectAll();

		request.setAttribute("list", settList);
		return "setting/list";
	}

	@RequestMapping("/add")
	public String add(HttpServletRequest request) {		
		return "setting/add";
	}

	@RequestMapping("/save")
	public String save(HttpServletRequest request,
			@RequestParam(value = "type", required = false) int type,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "cfield", required = false) String cfield,
			MultipartFile setingImg) {
		Setting setting = new Setting();
		setting.setType(type);
		setting.setName(name);
		setting.setCfield(cfield);
		setting.setState(1);
		if (setingImg.getSize() > 0L) {
			setting.setCfield1(StringUtil.uploadOnlyFile(request, setingImg));
		}
		int inster = settingService.insert(setting);

		return "redirect:/setting/list";
	}
	
	@RequestMapping("/delete")
	public String delete(HttpServletRequest request,
			@RequestParam(value = "Sid", required = false) Integer sid){
		
		settingService.deleteSetting(sid);
		
		return "redirect:/setting/list";
	}
	
	@RequestMapping("/changeType")
	@ResponseBody
	public JSONObject changeType(String type, JsonModel model){
		
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("type", type);
		List types = settingService.selectAllByType(map);
		if(types!=null && types.size() > 0){
			model.setjData(types);
		}else{
			model.setjData("");
		}
		
		return JSONObject.fromObject(model);
	}
}
